package cn.es.util;

import cn.es.pojo.Content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class HtmlParseUtil {
    public static void main(String[] args) throws IOException {
        System.out.println(HtmlParseUtil.getList("华为"));
//        String keyword="";
    }
    public static List<Content> getList(String keyword) throws IOException {
        //获取请求
        String url = "https://search.jd.com/Search?keyword="+keyword;
        //解析网页
        Document document = Jsoup.parse(new URL(url), 30000);
        Element element = document.getElementById("J_goodsList");
//        System.out.println(element.html());
        Elements elements = document.getElementsByTag("li");
        List<Content> contents=new ArrayList<>();
        int i=0;
        for (Element el:elements){

            if (el.attr("class").equalsIgnoreCase("gl-item"))         {
                String img = el.getElementsByTag("img").eq(0).attr("data-lazy-img");
                String price = el.getElementsByClass("p-price").eq(0).text();
                String title = el.getElementsByClass("p-name").eq(0).text();
//                System.out.println("============================");
//                System.out.println(img);
//                System.out.println(price);
//                System.out.println(title);
                contents.add(new Content(++i,title,img,price));
            }
        }
//        System.out.println(contents);
        return contents;
    }
}
